# -*- coding: utf8 -*-

from subprocess import Popen, PIPE
from archive import BaseAdapter, which
import os
from logger import get_file_logger

class P7ZipArchive(BaseAdapter):

    bin = which("7z")

    proc = None

    password = None

    pwd_file = "resource/passwords.txt"

    def _get_files( self ):
        names = []

        self.proc = Popen([
            self.bin,
            "l",
            "-p%s" % self.password,
            "-slt",
            "-bd",
            "-y",
            self.file_name
        ], stdout=PIPE)

        START = "----------"

        started = False

        item = {}

        while True:

            line = self.proc.stdout.readline()

            if line:

                line = line.strip().decode("utf-8")

                if line.startswith(START):
                    started = True
                    item = {}
                    continue

                if started:

                    if line == "":

                        if item["Attributes"].find("D") == -1:

                            names.append(item["Path"])

                        item = {}

                    else:
                        key = line.split("=")[0].strip()
                        value = "=".join(line.split("=")[1:]).strip()

                        item[key] = value
            else:
                if self.proc.poll() is not None:
                    break

        return names

    def get_files(self):

        names = []

        passwords = [""]

        log = get_file_logger("p7zip")

        if os.path.isfile(self.pwd_file):
            f = open(self.pwd_file)
            for l in f.readlines():
                l = l.strip()
                if l:
                    passwords.append(l)

        for p in passwords:
            self.password = p

            names = self._get_files()
            if len(names):
                if p:
                    log.info("Archive %r protected by password %r" % (self.file_name, self.password,))
                break

        return names

    def _extract_files( self, into_dir):

        dev_null = open(os.devnull, "w")
        self.proc = Popen([
            self.bin,
            "x",
            "-p%s" % self.password,
            "-bd",
            '-o%s' % into_dir,
            "-y",
            self.file_name
        ], stdout=dev_null, stderr=dev_null)
        ret = self.proc.wait()
        dev_null.close()

        return ret == 0

    def extract_files(self, into_dir):
        passwords = [""]

        if os.path.isfile(self.pwd_file):
            f = open(self.pwd_file)
            for l in f.readlines():
                l = l.strip()
                if l:
                    passwords.append(l)

        ret = False
        for p in passwords:
            self.password = p

            ret = self._extract_files(into_dir)
            if ret:
                break

        return ret

    def terminate(self):
        if self.proc and self.proc.poll() is None:
            self.proc.terminate()
        return

